#! /usr/bin/python
r''' 
``base16encode.py``

    :date: 20. Okt. 2011

'''

import base64
base = {
0 : '0', 1 : '1', 2 : '2', 3: '3', 4 :'4', 5 : '5', 6: '6',
7 : '7', 8 : '8', 9 :'9', 10: 'A', 11 : 'B', 12 : 'C',
13 :'D', 14 : 'E', 15 :'F'}

def base16encode(input_data):
    '''
encode data to base 16

:param input_data: data to be encoded (type ``str``)
:return: the base 16 presentation of ``input_data``
:rtype: ``str``
    '''
    
    binStr = ""
    encode = ""
    for i in range(len(input_data)):
        decimal_ascii = ord(input_data[i])
        binary = bin(decimal_ascii)
        split = binary[2:]
        while len(split) < 8:
            split = "0" + split
        binStr = binStr + split
       

    bitlaenge = len(binStr)
    anzahl_groups = bitlaenge / 4
   
    z = 0
    while z <= anzahl_groups-1:
        group = '0b' + binStr[z*4:(z+1)*4]
        z = z+1
        decimal = eval(group)
        
        if base.has_key(decimal):
            value = base.get(decimal)
            encode = encode + value
    print encode
    return encode

if __name__ =="__main__":

    test_file = 'avatar.jpg'
    file_desc = open(test_file)
    test_data = file_desc.read()
    stan_codierung = base64.b16encode(test_data)
    test_codierung = base16encode(test_data)

    print 'Standard:  ' +stan_codierung
    print 'Test    :  ' + test_codierung
    
    base16encode("")
    base16encode("f")
    base16encode("fo")
    base16encode("foo")
    base16encode("foob")
    base16encode("fooba")
    base16encode("foobar")